package abinly.harmony.permission;

import ohos.app.AbilityContext;
import ohos.bundle.IBundleManager;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Objects;

public final class PermissionHelper {

    private PermissionHelper() {
    }

    public static boolean verifySelfPermissions(AbilityContext context, String... permissions) {
        for (String permission : permissions) {
            if (!hasSelfPermission(context, permission)) {
                return false;
            }
        }
        return true;
    }

    public static boolean verifyCallingPermissions(AbilityContext context, String... permissions) {
        for (String permission : permissions) {
            if (!hasCallingPermission(context, permission)) {
                return false;
            }
        }
        return true;
    }

    public static boolean verifyCallingOrSelfPermissions(AbilityContext context, String... permissions) {
        for (String permission : permissions) {
            if (!hasCallingOrSelfPermission(context, permission)) {
                return false;
            }
        }
        return true;
    }

    public static boolean canRequestPermission(AbilityContext context, String... permissions){
        for (String permission : permissions) {
            if (!context.canRequestPermission(permission)) {
                return false;
            }
        }
        return true;
    }

    public static boolean verifyPermissions(int... grantResults) {
        if (grantResults.length == 0) {
            return false;
        }
        for (int result : grantResults) {
            if (result != IBundleManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private static boolean hasSelfPermission(AbilityContext context, String permission) {
        try {
            return context.verifySelfPermission(permission) == IBundleManager.PERMISSION_GRANTED;
        } catch (RuntimeException e) {
            return false;
        }
    }

    private static boolean hasCallingPermission(AbilityContext context, String permission) {
        try {
            return context.verifyCallingPermission(permission) == IBundleManager.PERMISSION_GRANTED;
        } catch (RuntimeException e) {
            return false;
        }
    }

    private static boolean hasCallingOrSelfPermission(AbilityContext context, String permission) {
        try {
            return context.verifyCallingOrSelfPermission(permission) == IBundleManager.PERMISSION_GRANTED;
        } catch (RuntimeException e) {
            return false;
        }
    }
}
